<template>
  <van-tabbar v-model="currentIndex" >
    <van-tabbar-item
        v-for="(item, index) in tabbarData"
        :key="index"
        replace
        :to="item.path"
    >
      <span>{{ item.title }}</span>
      <template #icon>
        <img
            :src="currentIndex === index ? item.activeIcon : item.icon"
            alt=""
            style="width: 1em; height: 1em;"
            v-if="isCustomIcon(item.icon) || isCustomIcon(item.activeIcon)"
        />
        <van-icon :name="item.icon" v-else />
      </template>
    </van-tabbar-item>
  </van-tabbar>
</template>

<script setup>
import { ref, watch } from 'vue';
import { useRoute } from "vue-router";
// 假设你已经把自定义图片放在了 src/assets 目录下
// 你需要根据实际图片名称进行修改
const tabbarData = [
  {
    title: '记录',
    icon: new URL('../assets/tabimgs/init_lemon.svg', import.meta.url).href, // 默认状态图片
    activeIcon: new URL('../assets/tabimgs/goal_lemon.svg', import.meta.url).href, // 选中状态图片
    path: '/record'
  },
  {
    title: '广场',
    icon: new URL('../assets/tabimgs/init_square.svg', import.meta.url).href, // 默认状态图片
    activeIcon: new URL('../assets/tabimgs/goal_square.svg', import.meta.url).href, // 选中状态图片
    path: '/square'
  },
  {
    title: '购物',
    icon: new URL('../assets/tabimgs/init_shop.svg', import.meta.url).href, // 默认状态图片
    activeIcon: new URL('../assets/tabimgs/goal_shop.svg', import.meta.url).href, // 选中状态图片
    path: '/shop'
  },
  {
    title: '我的',
    icon: new URL('../assets/tabimgs/init_personal.svg', import.meta.url).href, // 默认状态图片
    activeIcon: new URL('../assets/tabimgs/goal_personal.svg', import.meta.url).href, // 选中状态图片
    path: '/personal'
  },
]

const currentIndex = ref(0)
const route = useRoute()

// 根据当前路由设置选中的tab
const setActiveTab = () => {
  const paths = tabbarData.map(item => item.path)
  const currentPath = route.path
  const index = paths.findIndex(path => path === currentPath)
  if (index !== -1) {
    currentIndex.value = index
  }
}

// 监听路由变化
watch(() => route.path, () => {
  setActiveTab()
}, { immediate: true })

// 判断是否为自定义图标
const isCustomIcon = (icon) => {
  return typeof icon === 'string' && (icon.startsWith('http') || icon.includes('assets'));
}
</script>

<style lang="less" scoped>
</style>